import {Toast} from 'vant';
function formatTime(time:any) {
  let arr:any[] = []
  time = time.toLocaleDateString()

  time.replace(/\d+/g,(val:any) =>{
    val = val < 2 ? '0${val}' : val;
    arr.push(val)
  })
  return arr
}

const checkRouterParams = (query, needToast = false, needCheck = []) => {
  let flag = true
  if (!needCheck.length) {
    needCheck = ['userId', 'appKey']
  }
  for (let k = 0; k < needCheck.length; k++) {
    if (!query[needCheck[k]]) {
      needToast&&Toast('缺少'+needCheck[k]+'参数')
      flag = false
      break;
    }
  }
  return flag
}

const toastMsg = (res, that, url) => {
  let status = ''
  console.log('err', url)
  if (res && res.status) {
    status = res.status
  }
  if (res && res.data && (res.data.message || res.data.msg || res.data.m)) {
    // 因接口参数或是服务器错误导致的报错信息(带有message或msg的响应信息)
    let msg = res.data.message || res.data.msg || res.data.m || ''
    sessionStorage.setItem('errUrl', url + ':' + status + ':' + msg)  // 缓存报错的接口
    Toast({
      message: `${url}\ncode:` + status + ';' + msg,
      // message: msg,
      duration: 3000
    })
  } else if (res && res.data) { // 缺少appkey或是appSecret或userId错误以及网关相关报错信息
    // sessionStorage.setItem('errUrl', url + ':' + status + ':' + res.data) // 缓存报错的接口
    Toast({
      message: `${url}\ncode:` + status + ';' + res.data,
      // message: res.data,
      duration: 3000
    })
  } else { // 其他未知报错信息
    console.log('出现断网提示界面=====================', res)
    that.loadErr = true
    // Toast({
    //   message: `${url}\ncode:` + status + '; 网络不给力，请点击重试',
    //   duration: 3000
    // })
  }
}

const getDateStrs = (n) =>{
  var now = new Date()
  if (n) {
    now = new Date(now.getTime() - n * 24 * 60 * 60 * 1000)
  }
  var y = now.getFullYear();
  var m = ("0" + (now.getMonth() + 1)).slice(-2);
  var d = ("0" + now.getDate()).slice(-2);
  return y + "-" + m + "-" + d;
}

export default {
  formatTime,
  checkRouterParams,
  toastMsg,
  getDateStrs
}
